/*
 程序主入口
 在 cordova 新建项目上，增加了 updateApp
 修改以下 3 个参数：
 1、IOS 从服务端获取更新APP的路径
 var url_IOS = "http://m.dhbm.cn/app/qy/yltt/ios/";
 2、android API
 var apkUrl_APK = "http://api2.dhbm.cn:8080/getApkVersion.php?who=yltt_apk";
 3、IOS API
 var apkUrl_IPA = "http://api2.dhbm.cn:8080/getApkVersion.php?who=yltt_ipa";
 */


var app = {
    // Application Constructor
    initialize: function () {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        //add by wzh 20170125
        //这是自动触发事件
        this.listenAllChcpEvents();
    },


    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function () {
        //这个事件名称必须对应 html 里面 id="deviceready 名字：deviceready
        //佛则，找不到对应元素
        this.receivedEvent('deviceready');

        //设立放几个手工调用 chcp 事件
        document.getElementById('requestApplicationUpdate').addEventListener('click', app.requestApplicationUpdate);
        document.getElementById('isUpdateAvailableForInstallation').addEventListener('click', app.isUpdateAvailableForInstallation);
        document.getElementById('getVersionInfo').addEventListener('click', app.getVersionInfo);
        document.getElementById('fetchUpdate').addEventListener('click', app.fetchUpdate);
        document.getElementById('installUpdate').addEventListener('click', app.installUpdate);


        succCallbackl = function (res) {
            if (res == "IOS") {
                //alert("IOS app 升级");
                //var url_IOS = "http://m.dhbm.cn/app/qy/lmsd/ios/"; //可以从服务端获取更新APP的路径
                var url_IOS = "http://m.dhbm.cn/app/qy/yltt/ios/"; //可以从服务端获取更新APP的路径
                //window.open(url_IOS, '_system', 'location=yes');
                window.open(url_IOS, '_target');
            } else {
                console.log('succCallbackl 下载成功！1111112222' + res);
                //config 首页 去掉了 index.html，不用再跳转了
                // window.location.href = 'Home_yltt_index.html';
            }

        };
        errorCallback = function (res) {
            console.log('errorCallback 下载失败！ 1111112222 ' + res);
            //config 首页 去掉了 index.html，不用再跳转了
            // window.location.href = 'Home_yltt_index.html';
        };

        var apkUrl_APK = "http://api2.dhbm.cn:8080/getApkVersion.php?who=yltt_apk";
        var apkUrl_IPA = "http://api2.dhbm.cn:8080/getApkVersion.php?who=yltt_ipa";
        var apkUrl = "";
        //样本 : {"apk":"http://m.dhbm.cn/app/qy/lmsd/an/dhbm.lmsd.1.0.160707.apk","version":"1.0","sub":"160707"}

        var u = navigator.userAgent;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        //console.log("这是 ios 吗? =====" + isiOS);
        if (isiOS) {
            apkUrl = apkUrl_IPA;
        }
        else {
            //这是 android ，其他平台先忽略
            apkUrl = apkUrl_APK;
        }

        setTimeout(updateApp.checkUpdate(apkUrl, succCallbackl, errorCallback), 500);
    },

    // Update DOM on a Received Event
    receivedEvent: function (id) {
        console.log('接收到的事件 Received Event: ' + id);
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        // receivedElement.setAttribute('style', 'display:block;');
        receivedElement.setAttribute('style', 'display:none;');

        var u = navigator.userAgent;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        console.log("这是 ios 吗? 11112222 =====" + isiOS);
        if (isiOS) {
            //隐藏 android 特有的设置
            console.log("隐藏 android 特有的设置 2222 ");
            $(".android-Setting").hide();
        }
        else {
            //隐藏 android 特有的设置
            console.log("隐藏 ios 特有的设置 2222 ");
            $(".ios-Setting").hide();
        }

        getSuccCallback = function (version) {
            console.log("version ==== " + version);
            $("#appVersion").text("当前版本号 2222 ： " + version);
        };
        getFailCallback = function (res) {
            console.log(res);
        };

        cordova.getAppVersion.getVersionNumber(getSuccCallback, getFailCallback);


    },

    //add by wzh 20170125
    listenAllChcpEvents: function () {
        console.info("listenAllChcpEvents 9999999999====");
        //add by wzh 20170123 增加其他 listen 事件
        // Plugin events
        /*
         event: {
         BEFORE_ASSETS_INSTALLATION: 'chcp_beforeAssetsInstalledOnExternalStorage',
         ASSETS_INSTALLATION_FAILED: 'chcp_assetsInstallationError',
         ASSETS_INSTALLED: 'chcp_assetsInstalledOnExternalStorage',

         NOTHING_TO_UPDATE: 'chcp_nothingToUpdate',
         UPDATE_LOAD_FAILED: 'chcp_updateLoadFailed',
         UPDATE_IS_READY_TO_INSTALL: 'chcp_updateIsReadyToInstall',

         BEFORE_UPDATE_INSTALLATION: 'chcp_beforeInstall',
         UPDATE_INSTALLATION_FAILED: 'chcp_updateInstallFailed',
         UPDATE_INSTALLED: 'chcp_updateInstalled',
         NOTHING_TO_INSTALL: 'chcp_nothingToInstall'
         },
         */
        /*
         document.addEventListener('AAAchcp_beforeAssetsInstalledOnExternalStorage', this.onChcpUpdate('chcp_beforeAssetsInstalledOnExternalStorage'), false);
         document.addEventListener('AAAchcp_assetsInstallationError', this.onChcpUpdate('chcp_assetsInstallationError'), false);
         document.addEventListener('AAAchcp_assetsInstalledOnExternalStorage', this.onChcpUpdate('chcp_assetsInstalledOnExternalStorage'), false);

         document.addEventListener('AAAchcp_nothingToUpdate', this.onChcpUpdate('chcp_nothingToUpdate'), false);
         document.addEventListener('Achcp_updateLoadFailed', this.onChcpUpdate('chcp_updateLoadFailed'), false);
         document.addEventListener('Achcp_updateIsReadyToInstall', this.onChcpUpdate('chcp_updateIsReadyToInstall'), false);

         document.addEventListener('Achcp_beforeInstall', this.onChcpUpdate('chcp_beforeInstall'), false);
         document.addEventListener('Achcp_updateInstallFailed', this.onChcpUpdate('chcp_updateInstallFailed'), false);
         document.addEventListener('Achcp_updateInstalled', this.onChcpUpdate('chcp_updateInstalled'), false);
         document.addEventListener('Achcp_nothingToInstall', this.onChcpUpdate('chcp_nothingToInstall'), false);
         */
        document.addEventListener('chcp_beforeAssetsInstalledOnExternalStorage', function (e, msg) {
                console.info("收到事件 111666 events ====" + JSON.stringify(e));
                console.info("收到事件 111666 events ====" + JSON.stringify(msg));
                console.info("收到事件 111666 chcp_beforeAssetsInstalledOnExternalStorage ====");
            }
            , false
        );

        document.addEventListener('chcp_assetsInstallationError', function (e, msg) {
                console.info("收到事件 222666 events ====" + JSON.stringify(e));
                console.info("收到事件 222666 events ====" + JSON.stringify(msg));
                console.info("收到事件 222666 chcp_assetsInstallationError ====");
            }
            , false
        );
        document.addEventListener('chcp_assetsInstalledOnExternalStorage', function (e, msg) {
                console.info("收到事件 333666 events ====" + JSON.stringify(e));
                console.info("收到事件 333666 events ====" + JSON.stringify(msg));
                console.info("收到事件 333666 chcp_assetsInstalledOnExternalStorage ====");
            }
            , false
        );
        document.addEventListener('chcp_nothingToUpdate', function () {
                console.info("收到事件 444666 chcp_nothingToUpdate ==== 没有可以更新的内容 ");
            }
            , false
        );
        document.addEventListener('chcp_updateLoadFailed', function (e, msg) {
                console.info("收到事件 555666 events ====" + JSON.stringify(e));
                console.info("收到事件 555666 events ====" + JSON.stringify(msg));
                console.info("收到事件 555666 chcp_updateLoadFailed ====");
            }
            , false
        );
        document.addEventListener('chcp_updateIsReadyToInstall', function () {
                console.info("收到事件 777666 chcp_updateIsReadyToInstall ====");
                //在这里弹出提示：退出后再启动
                exitApp();
            }
            , false
        );
        document.addEventListener('chcp_beforeInstall', function (e, msg) {
                console.info("收到事件 888666 events ====" + JSON.stringify(e));
                console.info("收到事件 888666 events ====" + JSON.stringify(msg));
                console.info("收到事件 888666 chcp_beforeInstall ====");
            }
            , false
        );
        document.addEventListener('chcp_updateInstalled', function (e, msg) {
                console.info("收到事件 999666 events ====" + JSON.stringify(e));
                console.info("收到事件 999666 events ====" + JSON.stringify(msg));
                console.info("收到事件 999666 chcp_updateInstalled ====");
            }
            , false
        );

        document.addEventListener('chcp_nothingToInstall', function (e, msg) {
                console.info("收到事件 000666 events ====" + JSON.stringify(e));
                console.info("收到事件 000666 events ====" + JSON.stringify(msg));
                console.info("收到事件 000666 chcp_nothingToInstall ====");
            }
            , false
        );
    },

    requestApplicationUpdate: function () {
        console.log('点击了 requestApplicationUpdate  777');
        var onUserDismissedDialogCallback = function (res) {
            console.log('点击了 onUserDismissedDialogCallback  777' + JSON.stringify(res));
        };
        var onUserDismissedDialogCallback = function (res) {
            console.log('点击了 onUserDismissedDialogCallback  777' + JSON.stringify(res));
        };

        chcp.requestApplicationUpdate("发现有可以更新的内容，是否现在更新", onUserDismissedDialogCallback, onUserDismissedDialogCallback)
    },

    isUpdateAvailableForInstallation: function () {
        console.log('点击了 requestApplicationUpdate  666');
        /* res 样本
         {"code":1,"description":"Nothing to install"}"
         */
        chcp.isUpdateAvailableForInstallation(function (res) {
            console.log(' requestApplicationUpdate 的结果 777 ===' + JSON.stringify(res));
        })
    },

    fetchUpdate: function () {
        console.log('点击了 fetchUpdate 555');
        /* data 样本
         data = {"config":"{\n  \"name\": \"cdvDemo20161227\",\n  \"ios_identifier\": \"\",
         \n  \"android_identifier\": \"\",\n  \"update\": \"resume\",
         \n  \"content_url\": \"http://192.168.1.103/hot20170113/www\",
         \n  \"release\": \"2017.01.25-16.57.10\"\n}"}"
         */
        chcp.fetchUpdate(function (err, data) {
            console.log('fetchUpdate 888 的回调结果 err = ' + JSON.stringify(err));
            console.log('fetchUpdate 888 的回调结果 data = ' + JSON.stringify(data));
        })
    },

    getVersionInfo: function () {
        console.log('点击了 getVersionInfo  444');
        /* res 样本 ？怎么总是 null
         null
         */
        chcp.getVersionInfo(function (res) {
            console.log('点击了 getVersionInfo  444 res ==' + res);
        })
    },

    installUpdate: function () {
        console.log('点击了 installUpdate  333');
        /* res 样本
         res=={"code":1,"description":"Nothing to install"}"
         */
        chcp.installUpdate(function (res) {
            console.log('点击了 installUpdate  333 res==' + JSON.stringify(res));
        })
    }
};

app.initialize();

exitApp = function () {
    console.log("exitApp =============== exitApp");
    function alertDismissed() {
        console.log("navigator.app.exitApp");
        navigator.app.exitApp();
    }

    var mMessage = " 数据有更新，需要退出程序后，再次运行该程序";
    var mTitle = "退出程序提示 ..."
    navigator.notification.alert(
        mMessage,  // message
        alertDismissed,         // callback
        mTitle,            // title
        '好的'                  // buttonName
    );


}

